package jmeterBusiness;

import com.alibaba.fastjson.JSONObject;
import impl.TestServerBusinessImpl;
import models.GetRequestInputStream;
import models.HttpResponse;
import models.MyConfig;
import models.ReturnJson;
import tools.Http;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by yangxianming on 2017/7/7.
 * 启动远程serverNode执行jmeter脚本
 */
public class RunJmeterNode implements TestServerBusinessImpl {
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        ReturnJson returnJson = new ReturnJson();

        JSONObject jsonObject = GetRequestInputStream.getJson(request);
        String action = jsonObject.getString("action");
        String ip = jsonObject.getString("ip");
        String scriptName = jsonObject.getString("scriptName");

        String url = "http://" + ip + "/jmeter/runJmx";
        String param = "scriptName=" + scriptName;

        if (Objects.equals(action, "runNodeJmeter")){
            Http http = new Http();
            HttpResponse hr = http.sendRequest("get", null, url, param, 5000);
            if (hr.getrCode() == 200){
                String apiStatus = JSONObject.parseObject(hr.getResponseResult()).getString("apiStatus");
                if (Objects.equals(apiStatus, "1")){
                    returnJson.setApiStatus(1);
                    returnJson.setResult("ok");
                }
                if (Objects.equals(apiStatus, "0")){
                    returnJson.setApiStatus(0);
                    returnJson.setErrorMsg(JSONObject.parseObject(hr.getResponseResult()).getString("errorMsg"));
                }
            }else {
                returnJson.setApiStatus(0);
                returnJson.setErrorMsg("node cannot connect");
            }
        }
        if (Objects.equals(action, "checkJmeter")){
            Http http = new Http();
            HttpResponse hr = http.sendRequest("get", null, url, "action=isRun", 5000);
            if (hr.getrCode() != 200){
                returnJson.setApiStatus(2);
                returnJson.setErrorMsg("node cannot connect");
            }else {
                returnJson.setResult(JSONObject.parseObject(hr.getResponseResult()).getString("result"));
            }
        }


        return returnJson.toString();
    }

}
